<?php

/**
 * This is the model class for table "role".
 *
 * The followings are the available columns in table 'role':
 * @property string $RoleID
 * @property integer $MemberGroupID
 * @property integer $MenuAdminID
 * @property integer $IsView
 * @property integer $IsActive
 * @property integer $IsPublish
 * @property integer $IsAdd
 * @property integer $IsDelete
 * @property integer $IsEdit
 * @property integer $IsExport
 * @property integer $IsImport
 */
class Role extends CActiveRecord
{
	/**
	 * @return string the associated database table name
	 */
	public function tableName()
	{
		return 'role';
	}

	/**
	 * @return array validation rules for model attributes.
	 */
	public function rules()
	{
		// NOTE: you should only define rules for those attributes that
		// will receive user inputs.
		return array(
			array('MemberGroupID, MenuAdminID, IsView, IsActive, IsPublish, IsAdd, IsDelete, IsEdit, IsExport, IsImport', 'numerical', 'integerOnly'=>true),
			// The following rule is used by search().
			// @todo Please remove those attributes that should not be searched.
			array('RoleID, MemberGroupID, MenuAdminID, IsView, IsActive, IsPublish, IsAdd, IsDelete, IsEdit, IsExport, IsImport', 'safe', 'on'=>'search'),
		);
	}

	/**
	 * @return array relational rules.
	 */
	public function relations()
	{
		// NOTE: you may need to adjust the relation name and the related
		// class name for the relations automatically generated below.
		return array(
		);
	}

	/**
	 * @return array customized attribute labels (name=>label)
	 */
	public function attributeLabels()
	{
		return array(
			'RoleID' => 'Role',
			'MemberGroupID' => 'Nhóm',
			'MenuAdminID' => 'Tên menu',
			'IsView' => 'Xem',
			'IsActive' => 'Kích hoạt',
			'IsPublish' => 'Kiểm duyệt',
			'IsAdd' => 'Thêm',
			'IsDelete' => 'Xóa',
			'IsEdit' => 'Sửa',
			'IsExport' => 'Xuất bản',
			'IsImport' => 'Im port',
		);
	}

	/**
	 * Retrieves a list of models based on the current search/filter conditions.
	 *
	 * Typical usecase:
	 * - Initialize the model fields with values from filter form.
	 * - Execute this method to get CActiveDataProvider instance which will filter
	 * models according to data in model fields.
	 * - Pass data provider to CGridView, CListView or any similar widget.
	 *
	 * @return CActiveDataProvider the data provider that can return the models
	 * based on the search/filter conditions.
	 */
	public function search()
	{
		// @todo Please modify the following code to remove attributes that should not be searched.

		$criteria=new CDbCriteria;

		$criteria->compare('RoleID',$this->RoleID,true);
		$criteria->compare('MemberGroupID',$this->MemberGroupID);
		$criteria->compare('MenuAdminID',$this->MenuAdminID);
		$criteria->compare('IsView',$this->IsView);
		$criteria->compare('IsActive',$this->IsActive);
		$criteria->compare('IsPublish',$this->IsPublish);
		$criteria->compare('IsAdd',$this->IsAdd);
		$criteria->compare('IsDelete',$this->IsDelete);
		$criteria->compare('IsEdit',$this->IsEdit);
		$criteria->compare('IsExport',$this->IsExport);
		$criteria->compare('IsImport',$this->IsImport);

		return new CActiveDataProvider($this, array(
			'criteria'=>$criteria,
		));
	}

	/**
	 * Returns the static model of the specified AR class.
	 * Please note that you should have this exact method in all your CActiveRecord descendants!
	 * @param string $className active record class name.
	 * @return Role the static model class
	 */
	public static function model($className=__CLASS__)
	{
		return parent::model($className);
	}
   
   /**
    * Get all role
    * @param string limit
    * @return array role
   */
   public function getAll($limit = '',$params = array()){
      $limit = ($limit !='') ? ' LIMIT ' . $limit : '';
      $bindParam = '';
      if(count($params) > 0){
         foreach($params as $key=>$value){
            $bindParam .= " AND " . $this->tableName() . "." . $key . " =:" . $key ; 
         }
      }
      $sql =  "SELECT
               	role.MenuAdminID,
               	menuadmin.MenuAdminID,
               	membergroup.MemberGroupID as GroupID,
               	menuadmin.MenuName,
               	role.RoleID,
               	role.IsView,
               	role.IsActive,
               	role.IsPublish,
               	role.IsAdd,
               	role.IsDelete,
               	role.IsEdit,
               	membergroup.MembergroupName,
               	role.IsExport,
               	role.IsImport
               FROM
               	menuadmin
               INNER JOIN role ON menuadmin.MenuAdminID = role.MenuAdminID
               INNER JOIN membergroup ON membergroup.MemberGroupID = role.MemberGroupID
               WHERE 1 $bindParam
               $limit";
      $db = Yii::app()->db;
      $cmd = $db->createCommand($sql);
      if(count($params) > 0){
         foreach($params as $key=>$value){
            $cmd->bindParam(":".$key,$value);
         }
      }
      return $cmd->queryAll();
      
   }
   
   /**
    * Get right menu and user
    * @param string $idcontroller
   */
   public static function getRights($idController){
   
      $rights = array();
      $sql = "SELECT
     	         role.*
            FROM
            	role
            INNER JOIN menuadmin ON role.MenuAdminID = menuadmin.MenuAdminID
            WHERE MenuCode =:MenuCode";
      $db = Yii::app()->db;
      $cmd = $db->createCommand($sql);
      $cmd->bindParam(":MenuCode",$idController);
      $list = $cmd->queryAll();
      $users = array();  
      $i = 1;
      foreach($list as $item){
         
         $sql = "SELECT
                  	member.LoginName
                  FROM
                  	member
                  WHERE 
                     MemberGroupID =".$item['MemberGroupID'];
         $db = Yii::app()->db;
         $cmd = $db->createCommand($sql);
         //if($item)
         $users = $cmd->queryColumn(array("LoginName"));
         
         $rights[$i][0] = 'deny';
         if($item['IsView'] == 0){
            $rights[$i]['actions'][] = 'index';
            $rights[$i]['actions'][] = 'admin';
         }
         if($item['IsAdd'] == 0){
            $rights[$i]['actions'][] = 'create';
         }
         if($item['IsEdit'] == 0){
            $rights[$i]['actions'][] = 'edit';
         }
         if($item['IsDelete'] == 0){
            $rights[$i]['actions'][] = 'delete';
         }
         if($item['IsActive'] == 0){
            $rights[$i]['actions'][] = 'active';
            $rights[$i]['actions'][] = 'deactive';
            $rights[$i]['actions'][] = 'changeactive';
            $rights[$i]['actions'][] = 'changestatus';
         }
         if($item['IsPublish'] == 0){
            $rights[$i]['actions'][] = 'publish';
         }
         if($item['IsExport'] == 0){
            $rights[$i]['actions'][] = 'export';
         }
         if($item['IsImport'] == 0){
            $rights[$i]['actions'][] = 'import';
            $rights[$i]['actions'][] = 'upload';
         }
         $rights[$i]['actions'][] = 'default'; //Trường hợp user có tất cả các quyền với controller này
         $rights[$i]['users'] = (count($users) > 0) ? $users : array('default'); // Trường hợp nhóm này chưa có user nào
         
         $i++;
      }
      
      return $rights;
   }
   
   /**
    * Check and return right user
    * @param int idController
    * @return array
   */
   public static function checkRight($idController){
      $LoginName = Yii::app()->user->name;
      $sql = "SELECT
     	         role.*
            FROM
            	role
            INNER JOIN menuadmin ON role.MenuAdminID = menuadmin.MenuAdminID
            INNER JOIN member ON member.MemberGroupID = role.MemberGroupID
            WHERE 
               MenuCode =:MenuCode
            AND
	           LoginName =:LoginName";
      $db = Yii::app()->db;
      $cmd = $db->createCommand($sql);
      $cmd->bindParam(":MenuCode",$idController);
      $cmd->bindParam(":LoginName",$LoginName);
      return $cmd->queryRow();
   }
   
}
